package cn.longge.interceptor;

import cn.longge.entity.SysResource;
import cn.longge.service.ISysResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

public class ResourceInterceptor implements HandlerInterceptor {

    @Autowired
    private ISysResourceService resourceService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException, IOException {
        HttpSession session = request.getSession();
        List<SysResource> resources1 = (List<SysResource>) session.getAttribute("resources");
        List<SysResource> resources2 = resourceService.selectResource();
        String requestURI = request.getRequestURI();
        requestURI = requestURI.replace(request.getContextPath() + "/","");
        boolean flag = false;
        for (SysResource sysResource : resources2) {
            if(requestURI.equals(sysResource.getUrl())){
                flag = true;
                break;
            }
        }
        if(flag){
            for (SysResource sysResource : resources1) {
                if(requestURI.equals(sysResource.getUrl())){
                    return true;
                }
            }
            request.getRequestDispatcher("/WEB-INF/html/notauth.html").forward(request,response);
            return false;
        }else{
            return true;
        }
    }
}
